﻿using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using HotFixPackager.code;
using System.Text;

namespace HotFixPackager
{
    public partial class Form1 : Form
    {
        private static readonly string SETTING_URL = Environment.CurrentDirectory + "\\setting.data";
        private static readonly string GENERATE_OUT_DIR = Environment.CurrentDirectory + "\\out";
        private static readonly string PACK_CONFIG_FILE = Environment.CurrentDirectory + "\\bcpack.config";
        private static readonly string PACK_WORK_SPACE = GENERATE_OUT_DIR + "\\hotfix-working";
        private static readonly string PATCH_JAR= PACK_WORK_SPACE + "\\baichuan-hotfix-patch.jar";


        private AndFixConfig andfixConfig;

        public Form1()
        {
            InitializeComponent();

           if(File.Exists(SETTING_URL))
            {
                String str = File.ReadAllText(SETTING_URL);
                andfixConfig = ProtobufHelper.DeSerialize<AndFixConfig>(str);
            }
        }
        
        private void Form1_Load(object sender, EventArgs e)
        {
            if(andfixConfig==null)
            {
                andfixConfig = new AndFixConfig();
                return;
            }
            tbxPackJar.Text = andfixConfig.packJar;
            tbxOldApk.Text = andfixConfig.oldApk;
            tbxNewApk.Text = andfixConfig.newApk;
            tbxJks.Text = andfixConfig.jksUrl;
            tbxUserName.Text = andfixConfig.entryUserName;
            tbxUserPassword.Text = andfixConfig.entryPwd;
            tbxKeyPassword.Text = andfixConfig.jksPwd;
            ckbShowPackageDetail.Checked = andfixConfig.isShowPackageDetail;
        }

        private void btnNewApk_Click(object sender, EventArgs e)
        {
            selectApk(tbxNewApk);
        }

        private void btnOldApk_Click(object sender, EventArgs e)
        {
            selectApk(tbxOldApk);
        }

        private void btnJks_Click(object sender, EventArgs e)
        {
            selectFile(tbxJks, "秘钥文件|*.jks");
        }

        private void btnEngineJar_Click(object sender, EventArgs e)
        {
            selectFile(tbxPackJar, "打包工具jar|*.jar");
        }
        private void btnRun_Click(object sender, EventArgs e)
        {
            btnRun.Enabled = false;
            btnRun.Text = "正在打包中...";
            cleanDir();
            startCMD();
            String generatedPath = getPatchResult();

            if(generatedPath==null)
            {
                MessageBox.Show("打包失败，参数已经复制到剪贴板，请检查秘钥信息是否正确，新apk包是否新增、修改了函数、变量？");
            }
            else
            {
                MessageBox.Show("打包成功");
               Process.Start("Explorer", "/select," + generatedPath);
            }
            
            btnRun.Text = "生成修复包";
            btnRun.Enabled = true;
        }

        /// <summary>
        /// 清理上次打包目录
        /// </summary>
        void cleanDir()
        {
            DirectoryInfo workDir = new DirectoryInfo(PACK_WORK_SPACE);

            if(workDir.Exists)
            {
                workDir.Delete(true);
            }

            DirectoryInfo dir = new DirectoryInfo(GENERATE_OUT_DIR);
            if (dir.Exists)
            {
                dir.Delete(true);
            }
            dir.Create();
        }

        /// <summary>
        /// 开始调用打包bat
        /// </summary>
        void startCMD()
        {
            Process pro = new Process();
            pro.StartInfo.FileName = "java.exe";
            pro.StartInfo.Arguments = generatePackArg();
            
            if (!ckbShowPackageDetail.Checked)
            {
                pro.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            }

            pro.Start();
            pro.WaitForExit();
        }

        private String generatePackArg()
        {
            StringBuilder args = new StringBuilder();
            args.AppendFormat("-jar {0} -cmd patch",tbxPackJar.Text);
            args.AppendFormat(" -src_apk {0}", tbxOldApk.Text);
            args.AppendFormat(" -fixed_apk {0}", tbxNewApk.Text);
            args.AppendFormat(" -wp {0}", GENERATE_OUT_DIR);
            args.AppendFormat(getKey());
            string arg= args.ToString();
            Clipboard.SetDataObject("java "+ arg);
            return arg;
        }

        private String getKey()
        {
            StringBuilder sb = new StringBuilder();
            String jksPath = tbxJks.Text;
            sb.AppendFormat(" -sign_file_url {0}", jksPath);
            sb.AppendFormat(" -sign_file_pass {0}", tbxUserPassword.Text);
            sb.AppendFormat(" -sign_alias {0}", tbxUserName.Text);
            sb.AppendFormat(" -sign_alias_pass {0}", tbxKeyPassword.Text);
            return sb.ToString();
        }

        /// <summary>
        /// 清空打包出来后无用的文件
        /// </summary>
        /// <returns></returns>
        String getPatchResult()
        {
            return File.Exists(PATCH_JAR) ? PATCH_JAR : null;
        }
        
        void selectApk(TextBox tbx)
        {
            selectFile(tbx, "安装包|*.apk");
        }

        void selectFile(TextBox tbx,String filter)
        {
            fileDialog.FileName = tbx.Text;
            fileDialog.Filter = filter;
            fileDialog.Multiselect = false;

            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                tbx.Text = fileDialog.FileName;
            }
        }
 

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            andfixConfig.packJar = tbxPackJar.Text;
            andfixConfig.oldApk = tbxOldApk.Text;
            andfixConfig.newApk = tbxNewApk.Text;
            andfixConfig.jksUrl = tbxJks.Text;
            andfixConfig.entryUserName = tbxUserName.Text;
            andfixConfig.entryPwd = tbxUserPassword.Text;
            andfixConfig.jksPwd = tbxKeyPassword.Text;
            andfixConfig.isShowPackageDetail = ckbShowPackageDetail.Checked;

            String result = ProtobufHelper.Serialize<AndFixConfig>(andfixConfig);
            File.WriteAllText(SETTING_URL, result);
        }

      
    }
}
